import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import dotenv from 'dotenv';
import { createServer } from 'http';

import { DatabaseConnection } from '@/database/connection';
import { Logger } from '@/utils/logger';
import { errorHandler } from '@/middleware/errorHandler';
import { rateLimiter } from '@/middleware/rateLimiter';
import { requestLogger } from '@/middleware/requestLogger';

// 路由导入
import authRoutes from '@/routes/auth';
import healthRoutes from '@/routes/health';
import analysisRoutes from '@/routes/analysis';
import userRoutes from '@/routes/user';

// 加载环境变量
dotenv.config();

class HealthAssistantServer {
  private app: express.Application;
  private server: any;
  private logger = new Logger('Server');

  constructor() {
    this.app = express();
    this.initializeMiddleware();
    this.initializeRoutes();
    this.initializeErrorHandling();
  }

  private initializeMiddleware(): void {
    // 安全中间件
    this.app.use(helmet());
    
    // CORS配置
    this.app.use(cors({
      origin: process.env.CORS_ORIGIN || '*',
      credentials: true,
      optionsSuccessStatus: 200
    }));

    // 压缩中间件
    this.app.use(compression());

    // 请求解析
    this.app.use(express.json({ limit: '10mb' }));
    this.app.use(express.urlencoded({ extended: true, limit: '10mb' }));

    // 请求日志
    this.app.use(requestLogger);

    // 速率限制
    this.app.use(rateLimiter);

    // 健康检查端点
    this.app.get('/health', (req, res) => {
      res.status(200).json({
        status: 'healthy',
        timestamp: new Date().toISOString(),
        version: process.env.npm_package_version || '1.0.0'
      });
    });
  }

  private initializeRoutes(): void {
    const apiPrefix = '/api/v1';
    
    // API路由
    this.app.use(`${apiPrefix}/auth`, authRoutes);
    this.app.use(`${apiPrefix}/health`, healthRoutes);
    this.app.use(`${apiPrefix}/analysis`, analysisRoutes);
    this.app.use(`${apiPrefix}/user`, userRoutes);

    // 404处理
    this.app.use('*', (req, res) => {
      res.status(404).json({
        success: false,
        message: 'API endpoint not found',
        path: req.originalUrl
      });
    });
  }

  private initializeErrorHandling(): void {
    this.app.use(errorHandler);
  }

  public async start(): Promise<void> {
    try {
      // 初始化数据库
      await DatabaseConnection.initialize();
      this.logger.info('Database initialized successfully');

      // 启动服务器
      const port = process.env.PORT || 3000;
      const host = process.env.HOST || 'localhost';

      this.server = createServer(this.app);
      
      this.server.listen(port, host, () => {
        this.logger.info(`Server running on http://${host}:${port}`);
        this.logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
        this.logger.info('Health Assistant API is ready to serve requests');
      });

      // 优雅关闭处理
      this.setupGracefulShutdown();

    } catch (error) {
      this.logger.error('Failed to start server:', error);
      process.exit(1);
    }
  }

  private setupGracefulShutdown(): void {
    const gracefulShutdown = async (signal: string) => {
      this.logger.info(`Received ${signal}, starting graceful shutdown...`);
      
      if (this.server) {
        this.server.close(async () => {
          this.logger.info('HTTP server closed');
          
          try {
            await DatabaseConnection.close();
            this.logger.info('Database connection closed');
            
            this.logger.info('Graceful shutdown completed');
            process.exit(0);
          } catch (error) {
            this.logger.error('Error during graceful shutdown:', error);
            process.exit(1);
          }
        });
      }

      // 强制关闭超时
      setTimeout(() => {
        this.logger.error('Graceful shutdown timeout, forcing exit');
        process.exit(1);
      }, 10000);
    };

    // 监听关闭信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    
    // 未捕获异常处理
    process.on('uncaughtException', (error) => {
      this.logger.error('Uncaught Exception:', error);
      gracefulShutdown('uncaughtException');
    });

    process.on('unhandledRejection', (reason, promise) => {
      this.logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
      gracefulShutdown('unhandledRejection');
    });
  }

  public getApp(): express.Application {
    return this.app;
  }
}

// 启动服务器
const server = new HealthAssistantServer();

if (require.main === module) {
  server.start().catch((error) => {
    console.error('Failed to start server:', error);
    process.exit(1);
  });
}

export { HealthAssistantServer };
export default server.getApp();